import {defineStore} from 'pinia'
import {computed, ref} from 'vue'
import {useUserStore} from '@/stores/userStore.js'
import {deleteCartAPI, getCartListAPI, insertCartAPI} from '@/apis/cart.js'

export const useCartStore = defineStore('cart', () => {
	const userStore = useUserStore()
	// 是否登录
	const isLogin = computed(() => userStore.userInfo.token)

	// state
	const cartList = ref([])

	// action
	// 获取最新购物车列表
	const updateCartList = async () => {
		const res = await getCartListAPI()
		cartList.value = res.result
	}

	// 添加购物车
	const addCart = async (goods) => {
		const {skuId, count} = goods

		if (isLogin.value) {
			// 登录状态下的添加购物车
			// console.log(isLogin.value)
			await insertCartAPI({skuId, count})
			updateCartList()
		} else {
			// 添加购物车至本地
			// 如果goods中的数据已经在cartList中出现过，则count+1，没出现过直接push
			const item = cartList.value.find(item => item.skuId === goods.skuId)
			if (item) {
				// 购物车已经有该商品，数量加1
				item.count += goods.count
			} else {
				// 购物车无此商品，直接push
				cartList.value.push(goods)
			}
		}
	}

	// 删除购物车
	const delCart = async (id) => {
		if (isLogin.value) {
			// 调用删除购物车接口
			await deleteCartAPI([id])
			// 重新获取最新购物车数据
			updateCartList()
		} else {
			const index = cartList.value.findIndex(item => item.skuId === id)
			cartList.value.splice(index, 1)
		}
	}

	// 清空购物车
	const clearCart = () => {
		cartList.value = []
	}

	// 单选逻辑
	const singleCheck = (skuId, selected) => {
		const item = cartList.value.find(item => item.skuId === skuId)
		item.selected = selected
	}

	// 全选逻辑
	const allCheck = (selected) => {
		// 把cartList中的每一项的selected都设置为当前的全选框状态
		cartList.value.forEach(item => item.selected = selected)
	}

	// 计算属性求和（依赖的数据一旦发生变化，计算属性会立即重新计算）
	const allCount = computed(() => cartList.value.reduce((previousValue, currentValue) => previousValue + currentValue.count, 0))
	const allPrice = computed(() => cartList.value.reduce((previousValue, currentValue) => previousValue + currentValue.count * currentValue.price, 0))
	const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((previousValue, currentValue) => previousValue + currentValue.count, 0))
	const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((previousValue, currentValue) => previousValue + currentValue.count * currentValue.price, 0))
	// 全选框状态
	const isAll = computed(() => cartList.value.every(item => item.selected))

	return {
		cartList,
		addCart,
		delCart,
		allCount,
		allPrice,
		singleCheck,
		isAll,
		allCheck,
		selectedCount,
		selectedPrice,
		clearCart,
		updateCartList
	}
}, {
	persist: true
})
